package world.controllers

import com.github.pagehelper.PageHelper
import org.springframework.beans.factory.annotation.Value
import org.springframework.cache.annotation.Cacheable
import org.springframework.cache.annotation.EnableCaching
import org.springframework.transaction.annotation.Transactional
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestParam
import world.domain.UserMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody

@Controller
@RequestMapping(value="/user")
class UserController {

    @Autowired
    UserMapper userMapper

    @Value("\${ext.welcome}") //转义
    String welcome

    /**
     * 列表（JSON + 缓存）
     */
    @Cacheable("user")
    @ResponseBody
    @RequestMapping(value="/index")
    def index() {
        return userMapper.list()
    }

    /**
     * 列表（页面 + 分页）
     */
    @RequestMapping(value="/list")
    def list(Model model, @RequestParam(name="pageNum", defaultValue="1") Integer pageNum, @RequestParam(name="pageSize", defaultValue="1") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize)
        model.addAttribute("userList", userMapper.list())
        return "user/list"
    }

    /**
     * 读（事务-只读）
     */
    @Transactional(readOnly=true)
    @ResponseBody
    @RequestMapping(value="/show")
    def show(@RequestParam(name="id", defaultValue="3") String id) { //RequestParam注解，用于进行参数绑定。将请求参数绑定到方法参数（形参）上，同时支持设置默认值等操作
        userMapper.get(id)
    }

    @ResponseBody
    @RequestMapping(value="/save")
    def save(@RequestBody HashMap params) { //RequestBody注解，常用于接收JSON数据，而后进行数据类型转换，将其转换成指定类型的数据
        return userMapper.save([username:params.username, password:params.password, realname:params.realname])
    }

    /**
     * 改（事务）
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value="/update")
    def update(@RequestParam(name="id", defaultValue="3") String id, @RequestParam(name="realname", defaultValue="匿名君") String realname) {
        def user = userMapper.get(id)
        user.realname = realname
        return userMapper.update(user)
    }

    /**
     * 删（配置-读取）
     */
    @ResponseBody
    @RequestMapping(value="/delete")
    def delete(@RequestParam(name="id", defaultValue="3") String id) {
        println welcome
        println id
        def user = userMapper.get(id)
        userMapper.delete(user)
    }

    /**
     * 测试（JSP）
     */
    @RequestMapping(value="/test")
    def test(Model model) {
        model.addAttribute("userList", userMapper.list())
        return "user/test"
    }

}
